/**
 * Copyright 2020 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.dbfly.mybatis.builder.method;

import java.io.Serializable;

import com.jianggujin.dbfly.mybatis.constant.JOrderStrategy;
import com.jianggujin.dbfly.util.JStringUtils;

/**
 * 排序信息
 * 
 * @author jianggujin
 *
 */
public class JOrder implements Serializable {

    /**
     * 排序策略
     */
    private final JOrderStrategy strategy;
    /**
     * 排序属性
     */
    private final String property;

    /**
     * 通过指定属性排序
     * 
     * @param property
     * @return
     */
    public static JOrder by(String property) {
        return new JOrder(JSort.DEFAULT_DIRECTION, property);
    }

    /**
     * 通过指定属性升序排序
     * 
     * @param property
     * @return
     */
    public static JOrder asc(String property) {
        return new JOrder(JOrderStrategy.ASC, property);
    }

    /**
     * 通过指定属性降序排序
     * 
     * @param property
     * @return
     */
    public static JOrder desc(String property) {
        return new JOrder(JOrderStrategy.DESC, property);
    }

    public JOrder(JOrderStrategy direction, String property) {

        if (!JStringUtils.hasText(property)) {
            throw new IllegalArgumentException("Property must not null or empty!");
        }

        this.strategy = direction == null ? JSort.DEFAULT_DIRECTION : direction;
        this.property = property;
    }

    /**
     * 排序策略
     * 
     * @return
     */
    public JOrderStrategy getStrategy() {
        return strategy;
    }

    /**
     * 排序属性
     * 
     * @return
     */
    public String getProperty() {
        return property;
    }

    @Override
    public int hashCode() {
        int result = 17;
        result = 31 * result + strategy.hashCode();
        result = 31 * result + property.hashCode();

        return result;
    }

    @Override
    public boolean equals(Object obj) {

        if (this == obj) {
            return true;
        }
        if (!(obj instanceof JOrder)) {
            return false;
        }
        JOrder that = (JOrder) obj;
        return this.strategy.equals(that.strategy) && this.property.equals(that.property);
    }

    @Override
    public String toString() {
        return String.format("%s: %s", property, strategy);
    }
}
